package com.yc.star.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.star.entity.Team;
import com.yc.star.entity.User;
import com.yc.star.entity.UserTeam;
import com.yc.star.mapper.MaginformMapper;
import com.yc.star.mapper.TeamMapper;
import com.yc.star.mapper.UserTeamMapper;
import com.yc.star.vo.RedisUtil;
import com.yc.star.vo.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("team")
public class TeamDO {

    @Resource
    TeamMapper teamMapper;

    @Resource
    UserTeamMapper userTeamMapper;


    @Resource
    RedisUtil redisUtil;

    //@SessionAttribute(required = false)
    // required = false 表示这个属性是可选的。如果 session 中不存在该属性，
    // Spring MVC 不会抛出异常，而是将参数值设置为 null（或默认值，具体取决于参数类型）
    @RequestMapping("getTeam")
    public Result getTeam(HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        if (user == null) {
            return new Result(0, "请先登录", 1);
        }
        LambdaQueryWrapper<Team> lqw = new LambdaQueryWrapper();
        lqw.eq(Team::getUserid, user.getId());
//        lqw.eq(Team::getUserid, 1);
        List<Team> teams = teamMapper.selectList(lqw);
        for (Team team : teams) {
            LambdaQueryWrapper<UserTeam> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(UserTeam::getTeamid,team.getId());
            int aLong = Math.toIntExact(userTeamMapper.selectCount(lqw2))+1;
            team.setNum(aLong);
        }
        return new Result(1, "查找成功", teams);
    }

    @Transactional//创建队伍的同时还需要创建队伍和用户关系表star.s_user_team表
    //将队长添加到关系表中
    @RequestMapping("addTeam")//创建队伍
    public Result getTeam(@RequestBody Team team, HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        team.setUserid(user.getId());
        teamMapper.insert(team);
//        LambdaQueryWrapper<Team> lqw = new LambdaQueryWrapper();
//        lqw.eq(Team::getUserid,user.getId());
//        lqw.eq(Team::getName,team.getName());
//        lqw.eq(Team::getMaxNum,team.getMaxNum());
//        Team team1 = teamMapper.selectOne(lqw);
////        System.out.println(team1);
//        if (team1!=null){
//            UserTeam userTeam = new UserTeam();
//            userTeam.setUserid(user.getId());
//            userTeam.setTeamid(team1.getId());
//            userTeamMapper.insert(userTeam);
//        }
        System.out.println(11549);
        return new Result(1, "创建队伍成功", null);
    }

    @RequestMapping("matchteams")
    //有好友的推荐,队长标签匹配的推荐
    public Result matchTeams(HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user1 = (User) redisUtil.get(token);
        List<Team> teams = teamMapper.selectList(null);
        List<User> userRedis = (List<User>) redisUtil.get("userRedis");
        //数据量大时可优化
        int limit = Math.min(4, teams.size());  // 处理的最大数量
        for (int i = 0; i < limit; i++) {
            Team team = teams.get(i);
            for (User user : userRedis) {
                if (user.getId().equals(team.getUserid())) {
                    LambdaQueryWrapper<UserTeam> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(UserTeam::getTeamid,team.getId());
                    int aLong = Math.toIntExact(userTeamMapper.selectCount(lqw))+1;
                    team.setNum(aLong);
                    team.setHeader(user.getUsername());
                    break; // 找到匹配的用户后可以跳出内层循环
                }
            }
        }
        return new Result(1, "成功", teams);
    }

    @Resource
    MaginformMapper maginformMapper;

    /**
     *
     * @param id  队伍id
     * @param userid 队长id
     * @param request
     * @return
     */
    @RequestMapping("reqaddTeam")
    public Result reqAddTeam(@RequestParam("id") String id,@RequestParam("userid") String userid, HttpServletRequest request){
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
//        Maginform maginform = new Maginform();
//        maginform.setSenderId(user.getId());
//        maginform.setReceiverId(Long.valueOf(userid));
//        maginformMapper.insert(maginform);
        System.out.println(userid);
        if (userid.equals(user.getId().toString())){
            System.out.println(2641);
            return new Result(2,"队长队",null);
        }
        LambdaQueryWrapper<UserTeam> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserTeam::getUserid,user.getId());
        lqw.eq(UserTeam::getTeamid,Long.valueOf(id));
        Long aLong = userTeamMapper.selectCount(lqw);
        if (aLong!=0){
            return new Result(0,"error",null);
        }
        UserTeam userTeam = new UserTeam();
        userTeam.setTeamid(Long.valueOf(id));
        userTeam.setUserid(user.getId());
        LocalDateTime now = LocalDateTime.now();
        userTeam.setJoinTime(now);
        userTeamMapper.insert(userTeam);
        return new Result(1, "success", null);
    }


    @RequestMapping("getteams")
    public Result getTeams(HttpServletRequest request){
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);

        LambdaQueryWrapper<Team> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Team::getUserid,user.getId());
        List<Team> teams = teamMapper.selectList(lqw);
        System.out.println(teams);
        LambdaQueryWrapper<UserTeam> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(UserTeam::getUserid,user.getId());
        List<UserTeam> userTeams = userTeamMapper.selectList(lqw2);
        for (UserTeam userTeam:userTeams){
            Team team = teamMapper.selectById(userTeam.getTeamid());
            if (!teams.contains(team)){
                System.out.println(1);
                teams.add(team);
            }
        }
//        List<User> userRedis = (List<User>) redisUtil.get("userRedis");

        return new Result(1,"teams",teams);
    }
//    @Resource
//    private UserService userService;
//
//    @Resource
//    private TeamService teamService;
//
//    @Resource
//    private UserTeamService userTeamService;
//
//    @PostMapping("/add")
//    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
//        if (teamAddRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        Team team = new Team();
//        BeanUtils.copyProperties(teamAddRequest, team);
//        long teamId = teamService.addTeam(team, loginUser);
//        return ResultUtils.success(teamId);
//    }
//
//    @PostMapping("/update")
//    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
//        if (teamUpdateRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);
//        if (!result) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
//        }
//        return ResultUtils.success(true);
//    }
//
//    @GetMapping("/get")
//    public BaseResponse<Team> getTeamById(long id) {
//        if (id <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Team team = teamService.getById(id);
//        if (team == null) {
//            throw new BusinessException(ErrorCode.NULL_ERROR);
//        }
//        return ResultUtils.success(team);
//    }
//
//    @GetMapping("/list")
//    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
//        if (teamQuery == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        boolean isAdmin = userService.isAdmin(request);
//        // 1、查询队伍列表
//        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);
//        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
//        // 2、判断当前用户是否已加入队伍
//        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
//        try {
//            User loginUser = userService.getLoginUser(request);
//            userTeamQueryWrapper.eq("userId", loginUser.getId());
//            userTeamQueryWrapper.in("teamId", teamIdList);
//            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
//            // 已加入的队伍 id 集合
//            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
//            teamList.forEach(team -> {
//                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
//                team.setHasJoin(hasJoin);
//            });
//        } catch (Exception e) {
//        }
//        // 3、查询已加入队伍的人数
//        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
//        userTeamJoinQueryWrapper.in("teamId", teamIdList);
//        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
//        // 队伍 id => 加入这个队伍的用户列表
//        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
//        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
//        return ResultUtils.success(teamList);
//    }
//
//    // todo 查询分页
//    @GetMapping("/list/page")
//    public BaseResponse<Page<Team>> listTeamsByPage(TeamQuery teamQuery) {
//        if (teamQuery == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Team team = new Team();
//        BeanUtils.copyProperties(teamQuery, team);
//        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
//        Page<Team> resultPage = teamService.page(page, queryWrapper);
//        return ResultUtils.success(resultPage);
//    }
//
//    @PostMapping("/join")
//    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
//        if (teamJoinRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
//        return ResultUtils.success(result);
//    }
//
//    @PostMapping("/quit")
//    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
//        if (teamQuitRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
//        return ResultUtils.success(result);
//    }
//
//    @PostMapping("/delete")
//    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        long id = deleteRequest.getId();
//        User loginUser = userService.getLoginUser(request);
//        boolean result = teamService.deleteTeam(id, loginUser);
//        if (!result) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
//        }
//        return ResultUtils.success(true);
//    }
//
//
//    /**
//     * 获取我创建的队伍
//     *
//     * @param teamQuery
//     * @param request
//     * @return
//     */
//    @GetMapping("/list/my/create")
//    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
//        if (teamQuery == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        teamQuery.setUserId(loginUser.getId());
//        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
//        return ResultUtils.success(teamList);
//    }
//
//
//    /**
//     * 获取我加入的队伍
//     *
//     * @param teamQuery
//     * @param request
//     * @return
//     */
//    @GetMapping("/list/my/join")
//    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
//        if (teamQuery == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("userId", loginUser.getId());
//        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
//        // 取出不重复的队伍 id
//        // teamId userId
//        // 1, 2
//        // 1, 3
//        // 2, 3
//        // result
//        // 1 => 2, 3
//        // 2 => 3
//        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
//                .collect(Collectors.groupingBy(UserTeam::getTeamId));
//        List<Long> idList = new ArrayList<>(listMap.keySet());
//        teamQuery.setIdList(idList);
//        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
//        return ResultUtils.success(teamList);
//    }
}
